import { getUserInfo } from '@/apis/user';
import ButtonConfirm from '@/assets/button-confirm.png';
import ButtonReUpload from '@/assets/button-reupload.png';
import Bg from '@/assets/choise-bg.jpg';
import StartButton from '@/assets/drive-1.png';
import TipImage from '@/assets/join-1.png';
import ZhuanShu from '@/assets/render-5.png';
import BusNike from '@/components/Bus/Nike';
import Compressor from 'compressorjs';
import TweenOne from 'rc-tween-one';
import { history, useMutation, useQuery, useSearchParams } from 'umi';

import Title from '@/assets/drive-2.png';
import SubTitle from '@/assets/drive-3.png';

import { UploadManhuaAvatar } from '@/apis';
import { BUS_THEME, BusDetail, BusHead, JoinBus } from '@/apis/bus';
import BusZhuDi from '@/components/Bus/Zhudi';
import FixedButtons from '@/components/FixedButtons';
import '@animxyz/core';
import { XyzTransitionGroup } from '@animxyz/react';
import { useMemo } from 'react';
import { Toast } from 'react-vant';

// ## 需要携带参数 busId=xx
export default function Page() {
  const [searchParams] = useSearchParams();
  const busId = searchParams?.get('busId');

  const { data: user } = useQuery(['get:user'], getUserInfo);
  const { data: bus, refetch: refetchBus } = useQuery(['bus:detail'], () =>
    BusDetail({ id: busId! }),
  );

  // ?找到发起人
  const initiator = useMemo(() => bus?.passengers?.[0], [bus]);

  // ?上传头像
  const { mutateAsync, data: avatarRes } = useMutation(UploadManhuaAvatar, {
    onSuccess: async function (data) {},
  });

  // ?加入车队
  const { mutateAsync: mutateJoinAsync } = useMutation(JoinBus);

  // ?同步头像
  const { mutateAsync: mutateBusHeadAsync } = useMutation(BusHead, {
    onSuccess: function () {
      refetchBus();
    },
  });

  async function handleUpload(file: Blob | File) {
    Toast.loading({ message: '上传中', duration: 0 });
    new Compressor(file, {
      quality: 0.6,
      maxWidth: 1000,
      async success(result) {
        await mutateAsync(result);
        Toast.clear();
      },
      error(err) {
        console.log(err.message);
      },
    });
  }

  function handleTrickUploadClick() {
    const upload = document.querySelector(
      '.participants-upload-input-2',
    ) as HTMLElement;
    if (!upload) return;
    upload.click();
  }

  return (
    <>
      <FixedButtons />
      <XyzTransitionGroup
        appear
        appearVisible
        xyz="fade up-2 appear-stagger"
        className="bg-cover bg-no-repeat bg-center min-h-screen relative overflow-hidden pt-[120px]"
        style={{
          backgroundImage: `url(${Bg})`,
        }}
      >
        {/* nick name */}
        <div className=" flex justify-center items-center leading-none">
          <h4
            className=" text-[60px] text-[#a2ff3d] font-bold -translate-y-[4px]"
            style={{
              textShadow: '1px 1px 1px rgba(0,0,0,.3)',
            }}
          >
            @{initiator?.name}
          </h4>
          <i
            className="w-[158px] h-[78px] bg-cover block ml-1"
            style={{
              backgroundImage: `url(${ZhuanShu})`,
            }}
          ></i>
        </div>

        <h5
          className="w-[392px] h-[64px] bg-cover mt-2 mx-auto left-[20px] relative"
          style={{
            backgroundImage: `url(${Title})`,
          }}
        ></h5>
        <h6
          className="w-[264px] h-[84px] bg-cover mt-4 mx-auto"
          style={{
            backgroundImage: `url(${SubTitle})`,
          }}
        ></h6>

        {/* bus */}
        <div xyz="fade" className="relative">
          <TweenOne
            animation={{
              type: 'from',
              x: window.innerWidth + 500,
              duration: 3000,
            }}
            className="busContainer w-[1560px] relative -left-[410px] mt-[100px]"
          >
            {bus?.theme === BUS_THEME.NIKE && (
              <BusNike
                readonly
                selfAvatar={initiator?.head}
                friendAvatar={avatarRes?.img}
                onUploadSelfAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
                onUploadFriendAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
              />
            )}
            {bus?.theme === BUS_THEME.ZHUDI && (
              <BusZhuDi
                readonly
                selfAvatar={initiator?.head}
                friendAvatar={avatarRes?.img}
                onUploadSelfAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
                onUploadFriendAvatar={(e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  handleUpload(file);
                }}
              />
            )}
          </TweenOne>
        </div>

        {avatarRes?.img && (
          <button
            onClick={async () => {
              // ?点击确认先加入车队
              if (!bus?.id) return Toast('车队信息不存在!');

              const t = Toast.loading({ duration: 0 });
              await mutateJoinAsync({ busId: bus?.id });
              await mutateBusHeadAsync({
                busId: bus?.id,
                head: avatarRes?.img,
              });

              t.clear();
              history.replace(`/join/success?busId=${bus?.id}`);
            }}
            className="w-[472px] h-[90px] mx-auto block bg-cover active:scale-95 mb-2 mt-12"
            style={{
              backgroundImage: `url(${ButtonConfirm})`,
            }}
          />
        )}

        {avatarRes?.img && (
          <button
            onClick={() => {
              handleTrickUploadClick();
            }}
            className="w-[472px] h-[90px] mx-auto block bg-cover active:scale-95"
            style={{
              backgroundImage: `url(${ButtonReUpload})`,
            }}
          />
        )}

        {!avatarRes?.img && (
          <button
            onClick={() => {
              handleTrickUploadClick();
            }}
            className="w-[472px] h-[90px] bg-cover mx-auto block active:scale-95 mb-4 my-12"
            style={{
              backgroundImage: `url(${StartButton})`,
            }}
          ></button>
        )}

        {!avatarRes?.img && (
          <p
            className="w-[313px] h-[34px] bg-cover mx-auto block"
            style={{
              backgroundImage: `url(${TipImage})`,
            }}
          />
        )}
      </XyzTransitionGroup>
    </>
  );
}
